package com.atguigu.gmall.payment.service.impl;

import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.model.PaymentInfo;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * @author: atguigu
 * @create: 2023-06-27 15:43
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {


    /**
     * 用户选择一种付款方式后,保存本地交易记录
     *
     * @param paymentInfo 支付对象
     * @param paymentType 支付类型
     */
    @Override
    public void savePaymentInfo(PaymentInfo paymentInfo, String paymentType) {
        //1.先根据订单编号+付款方式查询本地交易记录 如果有直接返回 如没有再新增
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getPaymentType, paymentType);
        queryWrapper.and(a -> a.eq(PaymentInfo::getOrderId, paymentInfo.getOrderId()).or().eq(PaymentInfo::getOutTradeNo, paymentInfo.getOutTradeNo()));
        PaymentInfo one = this.getOne(queryWrapper);
        if (one != null) {
            return;
        }
        //2.构建本地支付交易对象并且保存
        this.save(paymentInfo);
    }

    /**
     * 根据订单编号+支付方式 查询本地交易记录
     *
     * @param outTradeNo
     * @param paymentType
     * @return
     */
    @Override
    public PaymentInfo getPaymentInfo(String outTradeNo, String paymentType) {
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getPaymentType, paymentType);
        queryWrapper.eq(PaymentInfo::getOutTradeNo, outTradeNo);
        return this.getOne(queryWrapper);
    }

    /**
     * 根据订单编号/订单ID +支付方式 查询本地交易记录
     *
     * @param orderId
     * @param paymentType
     * @return
     */
    @Override
    public PaymentInfo getPayInfoByOrderIdOrOutTradeNo(String orderId, String paymentType) {
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getPaymentType, paymentType);
        queryWrapper.and(a -> a.eq(PaymentInfo::getOrderId, orderId).or().eq(PaymentInfo::getOutTradeNo, orderId));
        PaymentInfo paymentInfo = this.getOne(queryWrapper);
        return paymentInfo;
    }
}
